//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package nc.impl.bd.material.baseinfo;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nc.bs.bd.ansydelete.AnsyDeleteMessageSender;
import nc.bs.bd.baseservice.md.BDSingleBaseService;
import nc.bs.bd.baseservice.md.VOArrayUtil;
import nc.bs.bd.baseservice.validator.RefPkExistsValidator;
import nc.bs.bd.cache.CacheProxy;
import nc.bs.bd.material.baseinfo.validator.MaterialAddClassDisableValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialBasClassUpdateValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialBaseClassValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialConvertValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialDataUpgradeValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialFeatureclassValueValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialIshproitemsValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialMainMeasdocRefValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialMeasRateValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialRetailRuleValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialTaxtypeUniqueValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialUniqueRuleValidator;
import nc.bs.bd.material.baseinfo.validator.MaterialUniqueUtil;
import nc.bs.bd.pub.ansy.ReallyTread;
import nc.bs.bd.service.ValueObjWithErrLog;
import nc.bs.businessevent.EventDispatcher;
import nc.bs.businessevent.UsePermChangeEvent;
import nc.bs.businessevent.bd.BDCommonEvent;
import nc.bs.businessevent.bd.BDCommonEventUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.core.service.TimeService;
import nc.bs.framework.core.util.ObjectCreator;
import nc.bs.framework.exception.ComponentNotFoundException;
import nc.bs.logging.Logger;
import nc.bs.ls.TaskConfigBuilder;
import nc.bs.uif2.validation.IValidationService;
import nc.bs.uif2.validation.NullValueValidator;
import nc.bs.uif2.validation.ValidationException;
import nc.bs.uif2.validation.ValidationFailure;
import nc.bs.uif2.validation.ValidationFrameworkUtil;
import nc.bs.uif2.validation.Validator;
import nc.itf.bd.defdoc.IDefdocQryService;
import nc.itf.bd.material.assign.IMaterialAssignService;
import nc.itf.bd.material.baseinfo.IMaterialBaseInfoEditValidatorForFrame;
import nc.itf.bd.material.baseinfo.IMaterialBaseInfoService;
import nc.itf.ls.ILightScheduler;
import nc.itf.uap.busibean.ISysInitQry;
import nc.itf.uapbd.pub.st.IStOperateService;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ArrayListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pub.billcode.itf.IBillcodeManage;
import nc.pub.billcode.vo.BillCodeContext;
import nc.pub.iufo.basedoc.OrgUtil;
import nc.pubitf.bd.material.IMaterailUpdateCheckForGL;
import nc.vo.bd.ansylog.AnsyDelLogVO;
import nc.vo.bd.config.BDModeSelectedVO;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.bd.errorlog.ErrLogResult;
import nc.vo.bd.errorlog.ErrLogReturnValue;
import nc.vo.bd.errorlog.ErrorLogUtil;
import nc.vo.bd.goodsref.GoodsRefVO;
import nc.vo.bd.material.MaterialConvertVO;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.material.cost.MaterialCostVO;
import nc.vo.bd.material.cost.MaterialCostmodeVO;
import nc.vo.bd.material.fi.MaterialFiVO;
import nc.vo.bd.material.marorg.MarOrgVO;
import nc.vo.bd.material.pfc.MaterialPfcSubVO;
import nc.vo.bd.material.pfc.MaterialPfcVO;
import nc.vo.bd.material.plan.MaterialPlanVO;
import nc.vo.bd.material.prod.MaterialProdVO;
import nc.vo.bd.material.pu.MaterialPuVO;
import nc.vo.bd.material.sale.MaterialBindleVO;
import nc.vo.bd.material.sale.MaterialSaleVO;
import nc.vo.bd.material.stock.MaterialReplVO;
import nc.vo.bd.material.stock.MaterialStockVO;
import nc.vo.bd.material.stock.MaterialWarhVO;
import nc.vo.bd.pub.SingleDistributedUpdateValidator;
import nc.vo.corg.CostRegionVO;
import nc.vo.jcom.lang.StringUtil;
import nc.vo.ls.TaskConfig;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.trade.sqlutil.IInSqlBatchCallBack;
import nc.vo.trade.sqlutil.InSqlBatchCaller;
import nc.vo.trade.voutils.IFilter;
import nc.vo.trade.voutils.VOUtil;
import nc.vo.uapbd.pub.util.SysParamUtils;
import nc.vo.util.AuditInfoUtil;
import nc.vo.util.BDAuditInfoUtil;
import nc.vo.util.BDModeManager;
import nc.vo.util.BDPKLockUtil;
import nc.vo.util.BDVersionValidationUtil;
import nc.vo.util.bizlock.BizlockDataUtil;
import nccloud.commons.collections.CollectionUtils;
import nccloud.commons.lang.ArrayUtils;
import nccloud.commons.lang.StringUtils;
import nccloud.itf.bd.material.hpc.IMaterialHpcService;
import net.sourceforge.pinyin4j.PinyinHelper;

public class MaterialBaseInfoServiceImpl extends BDSingleBaseService<MaterialVO> implements IMaterialBaseInfoService {
    private IMaterialAssignService assignService = null;
    private IBillcodeManage billcodeManage = null;
    private MaterialVersionDAO materialVersionDAO = null;
    private ILightScheduler lightScheduler;

    public MaterialBaseInfoServiceImpl() {
        super("c7dc0ccd-8872-4eee-8882-160e8f49dfad", new String[]{"materialconvert", "materialtaxtype"});
    }

    public ErrLogReturnValue copyInsertMaterial(MaterialVO vo, String pk_material) throws BusinessException {
        vo = this.insertVO(vo);
        return this.getAssignService().copyAssignMaterialByPk(vo, pk_material, true, false);
    }

    public ErrLogReturnValue createMaterialVersion(MaterialVO vo, String pk_material) throws BusinessException {
        MaterialVO oldVO = this.queryOldVO(pk_material);
        this.lockSourcePKs(oldVO);
        BizlockDataUtil.lockDataByBizlock(new CircularlyAccessibleValueObject[]{vo});
        BDVersionValidationUtil.validateSuperVO(new SuperVO[]{oldVO});
        vo = this.getNewVersionData(vo, oldVO);
        this.insertValidateVO(vo);
        this.setInsertAuditInfo(vo);
        this.fireBeforeInsertEvent(vo);
        String pk = super.dbInsertVO(vo);
        vo.setPrimaryKey(pk);
        this.updateMaterialLatesetFlag(vo.getPk_source(), vo.getVersion() - 1, false);
        this.getMaterialVersionDAO().updateMaterialVersion(vo);
        vo = (MaterialVO)this.retrieveVO(pk);
        this.notifyVersionChangeWhenDataInserted(vo);
        this.fireAfterInsertEvent(vo);
        MaterialVO[] vos = this.synMaterialCode(vo, oldVO);
        ErrLogReturnValue result = this.getAssignService().copyAssignMaterialByPk(vo, pk_material, false, false);
        this.getBusiLogUtil().writeBusiLog("createversion", (String)null, new SuperVO[]{vo});
        return new ErrLogReturnValue(result.getErrLogResult(), new Object[]{vo, vos}, result.getTotalNum());
    }

    public void deleteMaterial(MaterialVO vo) throws BusinessException {
        if (vo != null && vo.getEnablestate() != null && vo.getEnablestate().equals(1)) {
            this.deleteVONoCheck(vo);
        } else {
            this.deleteVO(vo);
        }

    }

    public void deleteVONoCheck(MaterialVO vo) throws BusinessException {
        if (vo != null) {
            this.deletelockOperate(vo);
            BDVersionValidationUtil.validateSuperVO(new SuperVO[]{vo});
            this.notifyVersionChangeWhenDataDeleted(vo);
            this.dbDeleteVO(vo);
            this.writeDeletedBusiLog(vo);
        }
    }

    public ValueObjWithErrLog disableMaterial(MaterialVO[] vos) throws BusinessException {
        return this.disableVO(vos);
    }

    public ValueObjWithErrLog disableMaterial_RequiresNew(MaterialVO materialVO) throws BusinessException {
        return null;
    }

    public ValueObjWithErrLog enableMaterial(MaterialVO[] vos) throws BusinessException {
        List<String> pk_materialList = new ArrayList();

        for(MaterialVO vo : vos) {
            if (vo != null && vo.getEnablestate() != null && vo.getEnablestate().equals(1) && vo.getPk_org().equals(vo.getPk_group())) {
                pk_materialList.add(vo.getPk_material());
            }
        }

        if (pk_materialList != null && pk_materialList.size() > 0) {
            String pk_group = InvocationInfoProxy.getInstance().getGroupId();
            this.getAssignService().assignMaterialByPks((String[])pk_materialList.toArray(new String[0]), new String[]{pk_group}, (String[])null);
        }

        ValueObjWithErrLog log = this.enableVO(vos);
        this.dealWithAnsyLog(vos);
        MaterialVO[] materialvos = (MaterialVO[])VOArrayUtil.convertToVOArray(MaterialVO.class, log.getVos());
        this.getBaseDAO().updateVOArray(this.resetMaterialvos(materialvos), new String[]{"deletestate", "delperson", "deltime"});
        SuperVO[] afterupdatevos = this.getAfterUpdatevos(materialvos);
        log.setVos(afterupdatevos);
        return log;
    }

    private MaterialVO[] resetMaterialvos(MaterialVO[] vos) {
        if (vos != null && vos.length > 0) {
            for(int i = 0; i < vos.length; ++i) {
                vos[i].setDeletestate(0);
                vos[i].setDelperson((String)null);
                vos[i].setDeltime((UFDateTime)null);
            }
        }

        return vos;
    }

    private void dealWithAnsyLog(MaterialVO[] vos) throws BusinessException {
        List<String> list = VOUtil.extractFieldValues(vos, "pk_material", (IFilter)null);
        InSqlBatchCaller caller = new InSqlBatchCaller((String[])list.toArray(new String[0]));

        try {
            List<AnsyDelLogVO> ansylist = (List)caller.execute(new IInSqlBatchCallBack() {
                List<AnsyDelLogVO> list = new ArrayList();

                public Object doWithInSql(String inSql) throws BusinessException, SQLException {
                    Collection<AnsyDelLogVO> col = MaterialBaseInfoServiceImpl.this.getBaseDAO().retrieveByClause(AnsyDelLogVO.class, "pk_basdoc in " + inSql);
                    if (col != null && col.size() > 0) {
                        this.list.addAll(col);
                    }

                    return this.list;
                }
            });
            this.getBaseDAO().deleteVOList(ansylist);
        } catch (SQLException e) {
            Logger.error(e.getMessage(), e);
            throw new BusinessException(e.getMessage(), e);
        }
    }

    public MaterialVersionDAO getMaterialVersionDAO() {
        if (this.materialVersionDAO == null) {
            this.materialVersionDAO = new MaterialVersionDAO();
        }

        return this.materialVersionDAO;
    }

    public MaterialVO insertMaterial(MaterialVO vo) throws BusinessException {
        this.defaultValues(vo);
        ISysInitQry sysInitQry = (ISysInitQry)NCLocator.getInstance().lookup(ISysInitQry.class);
        UFBoolean HRP01 = sysInitQry.getParaBoolean(vo.getPk_group(), "BD_HRP01");
        if (vo.getPk_group().equals(vo.getPk_org())) {
            if (HRP01 != null && HRP01.booleanValue()) {
                vo.setIfassign(new UFBoolean(true));
            }
        } else {
            vo.setIfassign(new UFBoolean(true));
        }

        vo = this.insertVO(vo);
        if (this.isVOFromPF(vo)) {
            return vo;
        } else {
            if (vo != null && vo.getEnablestate() != null && vo.getEnablestate().equals(1)) {
                if (!vo.getPk_org().equals(vo.getPk_group())) {
                    this.getAssignService().assignMaterialToSelfOrgWithAdd(vo);
                }
            } else {
                this.getAssignService().assignMaterialToSelfOrgWithAdd(vo);
            }

            return vo;
        }
    }

    private void defaultValues(MaterialVO vo) throws BusinessException {
        if (vo.getFlag_onlycharge() != null && vo.getFlag_onlycharge().booleanValue()) {
            vo.setCharge(new UFBoolean(true));
        }

        MaterialConvertVO[] _vos = vo.getMaterialconvert();
        if (_vos != null && _vos.length > 0) {
            for(MaterialConvertVO convert : _vos) {
                UFBoolean flag_drug = vo.getFlag_drug();
                if (flag_drug != null && flag_drug.booleanValue() && convert.getIsstockmeasdoc().booleanValue()) {
                    String pk_measdoc = convert.getPk_measdoc();
                    String pk_measdoc_base = vo.getPk_measdoc_base();
                    if (!pk_measdoc_base.equals(pk_measdoc)) {
                        throw new BusinessException("药品档案保存时需要库存单位与基本计量单位一致!");
                    }
                }
            }
        }

    }

    private Boolean addSupplierPrice(String[] pk_org_arr, String[] pk_material_arr) throws BusinessException {
        if (!ArrayUtils.isEmpty(pk_org_arr) && !ArrayUtils.isEmpty(pk_material_arr)) {
            if (SysParamUtils.isEnableST() && SysParamUtils.isOperateSupplierPirce()) {
                IStOperateService stOperateService = (IStOperateService)NCLocator.getInstance().lookup(IStOperateService.class);
                return stOperateService.addSupplierPrice(pk_org_arr, pk_material_arr);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private boolean isVOFromPF(MaterialVO vo) {
        return vo.getPk_material_pf() != null;
    }

    public MaterialVO insertVO(MaterialVO vo) throws BusinessException {
        this.checkRequiredProperties(new MaterialVO[]{vo});
        this.dealDrugInfo(new MaterialVO[]{vo});
        this.dealMarAsstFrameInfo(new MaterialVO[]{vo});
        this.dealMaterialmnecode(new MaterialVO[]{vo});
        BillCodeContext billCodeContext = this.getBillcodeManage().getBillCodeContext("material", vo.getPk_group(), vo.getPk_org());
        vo.setVersion(1);
        vo.setPk_source((String)null);
        vo.setLatest(UFBoolean.TRUE);
        if (vo.getEnablestate() == null) {
            vo.setEnablestate(2);
        }

        vo = this.insertWithAutoCode(vo, billCodeContext);
        if (billCodeContext != null && billCodeContext.isPrecode()) {
            this.getBillcodeManage().commitPreBillCode("material", vo.getPk_group(), vo.getPk_org(), vo.getCode());
        }

        return vo;
    }

    public MaterialVO[] updateMaterial(MaterialVO vo) throws BusinessException {
        if (vo == null) {
            return null;
        } else {
            this.checkRequiredProperties(new MaterialVO[]{vo});
            this.dealDrugInfo(new MaterialVO[]{vo});
            this.dealMarAsstFrameInfo(new MaterialVO[]{vo});
            this.dealMaterialmnecode(new MaterialVO[]{vo});
            this.updatelockOperate(vo);
            BDVersionValidationUtil.validateSuperVO(new SuperVO[]{vo});
            MaterialVO oldVO = (MaterialVO)this.retrieveVO(vo.getPrimaryKey());
            this.setVersionField(vo, oldVO);
            this.updateValidateVO(oldVO, vo);
            vo.setPk_material_pf(oldVO.getPk_material_pf());
            MaterialVO[] oldVOs = this.queryMaterialOldVOsWhenCodeChanged(vo, oldVO);
            MaterialVO[] vos = this.getSynCodeVOs(vo, oldVOs);
            BDAuditInfoUtil.updateData(new SuperVO[]{vo});
            BDAuditInfoUtil.updateData(vos);
            BDCommonEventUtil eventUtil = new BDCommonEventUtil(this.getMDId());
            eventUtil.setOldObjs(ArrayUtils.add(oldVOs, 0, oldVO));
            eventUtil.dispatchUpdateBeforeEvent(ArrayUtils.add(vos, 0, vo));
            this.getPersistenceUtil().updateVO(new MaterialVO[]{vo});
            String[] fields = new String[]{"code", "modifier", "modifiedtime"};
            this.getPersistenceUtil().updateVOWithAttrs(fields, vos);
            MaterialVO latestVO = this.getLatestVO(vo, vos);
            if (latestVO != null) {
                this.getMaterialVersionDAO().updateMaterialVersion(latestVO);
            }

            this.notifyVersionChangeWhenDataUpdated(vo);
            String[] pks = VOArrayUtil.getPrimaryKeyArray(vos);
            vos = (MaterialVO[])this.retrieveVO((String[])ArrayUtils.add(pks, 0, vo.getPrimaryKey()));
            this.writeUpdatedBusiLog(oldVO, vo);
            eventUtil.dispatchUpdateAfterEvent((Object[])vos);
            this.deleteGoodsRef(oldVO, vo);
            return vos;
        }
    }

    public ErrLogReturnValue upgradeMaterials(MaterialVO[] vos) throws BusinessException {
        String pk_user = InvocationInfoProxy.getInstance().getUserId();
        ErrorLogUtil util = new ErrorLogUtil("c7dc0ccd-8872-4eee-8882-160e8f49dfad", pk_user, NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0129"), false);
        if (vos != null && vos.length != 0) {
            BDModeSelectedVO bdmodeVO = BDModeManager.getInstance().getBDModeSelectedVOByMDClassID("c7dc0ccd-8872-4eee-8882-160e8f49dfad");
            if (6 != bdmodeVO.getManagemode()) {
                throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0130"));
            } else {
                this.lockSourcePKs(vos);
                BDVersionValidationUtil.validateSuperVO(vos);
                Map<String, MaterialVO> upgradeMap = new HashMap();

                for(int i = 0; i < vos.length; ++i) {
                    if (!StringUtils.equals(vos[i].getPk_org(), vos[i].getPk_group())) {
                        upgradeMap.put(vos[i].getPk_source(), vos[i]);
                    }
                }

                if (upgradeMap.isEmpty()) {
                    throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0131"));
                } else {
                    Map<String, List<MaterialVO>> sourcePk_voList_map = this.queryAllVersionData((String[])upgradeMap.keySet().toArray(new String[0]));
                    if (sourcePk_voList_map != null && !sourcePk_voList_map.isEmpty()) {
                        Map<String, MaterialVO> pk_oldVO_map = new HashMap();
                        int count = 0;
                        List<MaterialVO> material_list = new ArrayList();

                        for(String pk_source : sourcePk_voList_map.keySet()) {
                            List<MaterialVO> list = (List)sourcePk_voList_map.get(pk_source);

                            for(MaterialVO materialVO : list) {
                                pk_oldVO_map.put(materialVO.getPrimaryKey(), (MaterialVO)materialVO.clone());
                                materialVO.setPk_org(materialVO.getPk_group());
                                material_list.add(materialVO);
                            }

                            ++count;
                            BizlockDataUtil.lockDataByBizlock((CircularlyAccessibleValueObject[])list.toArray(new MaterialVO[0]));
                        }

                        this.filterBreakUniqueRuleSelfVOs(sourcePk_voList_map, util);
                        this.filterCanUpgradeVO(sourcePk_voList_map, util);
                        if (sourcePk_voList_map != null && sourcePk_voList_map.size() > 0) {
                            List<MaterialVO> toUpdateVOList = new ArrayList();

                            for(List<MaterialVO> list : sourcePk_voList_map.values()) {
                                toUpdateVOList.addAll(list);
                            }

                            vos = (MaterialVO[])toUpdateVOList.toArray(new MaterialVO[0]);
                            MaterialVO[] oldVOs = new MaterialVO[vos.length];

                            for(int i = 0; i < vos.length; ++i) {
                                oldVOs[i] = (MaterialVO)pk_oldVO_map.get(vos[i].getPrimaryKey());
                            }

                            BDAuditInfoUtil.addData(vos);
                            EventDispatcher.fireEvent(new BDCommonEvent(this.getMDId(), "1064", oldVOs, vos));
                            String[] updateFields = new String[]{"pk_org", "modifier", "modifiedtime"};
                            this.getBaseDAO().updateVOArray(vos, updateFields);
                            this.synMaterialVersionForUpgrade(vos, updateFields);
                            if (material_list != null && material_list.size() > 0) {
                                this.assignMaterial((MaterialVO[])material_list.toArray(new MaterialVO[0]));
                            }

                            CacheProxy.fireDataUpdated(vos[0].getTableName());
                            vos = (MaterialVO[])this.retrieveVO(VOArrayUtil.getPrimaryKeyArray(vos));
                            EventDispatcher.fireEvent(new BDCommonEvent(this.getMDId(), "1065", oldVOs, vos));
                            EventDispatcher.fireEvent(new UsePermChangeEvent(this.getMDId(), "dataperm_change"));
                            this.getBusiLogUtil().writeModefyBusiLog("upgrade", vos, oldVOs);
                        }

                        return util.getErrLogReturnValue(vos, count);
                    } else {
                        throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0132"));
                    }
                }
            }
        } else {
            return null;
        }
    }

    protected void dbDeleteVO(MaterialVO vo) throws BusinessException {
        this.deleteMaterialTab(vo);
        super.dbDeleteVO(vo);
        this.synMaterialVersionForDelete(vo);
    }

    private void deleteMaterialTab(MaterialVO vo) throws BusinessException {
        String pk_material = vo.getPk_material();

        try {
            this.getBaseDAO().deleteByClause(MarOrgVO.class, "pk_material='" + pk_material + "'");
            this.getBaseDAO().deleteByClause(MaterialFiVO.class, "pk_material='" + pk_material + "'");
            this.getBaseDAO().deleteByClause(MaterialPuVO.class, "pk_material='" + pk_material + "'");
            this.getBaseDAO().deleteByClause(MaterialProdVO.class, "pk_material='" + pk_material + "'");
            BaseDAO var10000 = this.getBaseDAO();
            String var10002 = MaterialSaleVO.getDefaultTableName();
            var10000.deleteByClause(MaterialBindleVO.class, "pk_materialsale in( select pk_materialsale from " + var10002 + " where pk_material = '" + pk_material + "')");
            this.getBaseDAO().deleteByClause(MaterialSaleVO.class, "pk_material='" + pk_material + "'");
            var10000 = this.getBaseDAO();
            var10002 = MaterialPfcVO.getDefaultTableName();
            var10000.deleteByClause(MaterialPfcSubVO.class, "pk_materialpfc in( select pk_materialpfc from " + var10002 + " where pk_material = '" + pk_material + "')");
            this.getBaseDAO().deleteByClause(MaterialPfcVO.class, "pk_material='" + pk_material + "'");
            var10000 = this.getBaseDAO();
            var10002 = MaterialPlanVO.getDefaultTableName();
            var10000.deleteByClause(MaterialReplVO.class, "pk_materialplan in( select pk_materialplan from " + var10002 + " where pk_material = '" + pk_material + "')");
            this.getBaseDAO().deleteByClause(MaterialPlanVO.class, "pk_material='" + pk_material + "'");
            var10000 = this.getBaseDAO();
            var10002 = MaterialStockVO.getDefaultTableName();
            var10000.deleteByClause(MaterialWarhVO.class, "pk_materialstock in( select pk_materialstock from " + var10002 + " where pk_material = '" + pk_material + "')");
            this.getBaseDAO().deleteByClause(MaterialStockVO.class, "pk_material='" + pk_material + "'");
            var10000 = this.getBaseDAO();
            var10002 = MaterialCostVO.getDefaultTableName();
            var10000.deleteByClause(MaterialCostmodeVO.class, "pk_materialcost in( select pk_materialcost from " + var10002 + " where pk_material = '" + pk_material + "')");
            this.getBaseDAO().deleteByClause(MaterialCostVO.class, "pk_material='" + pk_material + "'");
        } catch (DAOException e) {
            Logger.error(e.getMessage());
        }

    }

    protected void dbDisableVO(MaterialVO... vos) throws BusinessException {
        super.dbDisableVO(vos);
        String[] fields = new String[]{"enablestate", "modifier", "modifiedtime"};
        this.getMaterialVersionDAO().updateMaterialVersion(fields, vos);
    }

    protected void dbEnableVO(MaterialVO... vos) throws BusinessException {
        super.dbEnableVO(vos);
        String[] fields = new String[]{"enablestate", "modifier", "modifiedtime"};
        this.getMaterialVersionDAO().updateMaterialVersion(fields, vos);
    }

    protected String dbInsertVO(MaterialVO vo) throws BusinessException {
        String pk_material = super.dbInsertVO(vo);
        vo.setPk_material(pk_material);
        vo.setPk_source(pk_material);
        this.getBaseDAO().updateVO(vo, new String[]{"pk_source"});
        this.getMaterialVersionDAO().insertMaterialVersion(vo);
        return pk_material;
    }

    protected void deletelockOperate(MaterialVO vo) throws BusinessException {
        this.lockSourcePKs(vo);
        super.deletelockOperate(vo);
    }

    protected Validator[] getInsertValidator() {
        NullValueValidator notNullValidator = NullValueValidator.createMDNullValueValidator(MaterialVO.class.getName(), Arrays.asList("pk_group", "pk_org", "code", "name", "pk_marbasclass", "pk_measdoc", "pk_mattaxes", "enablestate", "version"));
        MaterialMeasRateValidator measRateValidator = new MaterialMeasRateValidator();
        MaterialConvertValidator convertValidator = new MaterialConvertValidator((MaterialVO)null);
        MaterialTaxtypeUniqueValidator taxtypeUniqueValidator = new MaterialTaxtypeUniqueValidator((MaterialVO)null);
        RefPkExistsValidator refExistsValidator = new RefPkExistsValidator(new String[]{"pk_marbasclass"});
        MaterialBaseClassValidator classValidator = new MaterialBaseClassValidator();
        MaterialAddClassDisableValidator classDisableValidator = new MaterialAddClassDisableValidator();
        MaterialUniqueRuleValidator uniqueValidator = new MaterialUniqueRuleValidator();
        MaterialRetailRuleValidator retailRuleValidator = new MaterialRetailRuleValidator((MaterialVO)null);
        MaterialIshproitemsValidator ishproitemsValidator = new MaterialIshproitemsValidator();
        MaterialFeatureclassValueValidator featureclassValueValidator = new MaterialFeatureclassValueValidator();
        return new Validator[]{notNullValidator, measRateValidator, convertValidator, taxtypeUniqueValidator, refExistsValidator, classValidator, classDisableValidator, uniqueValidator, retailRuleValidator, ishproitemsValidator, featureclassValueValidator};
    }

    protected Validator[] getUpdateValidator(MaterialVO oldVO) {
        NullValueValidator notNullValidator = NullValueValidator.createMDNullValueValidator(MaterialVO.class.getName(), Arrays.asList("pk_group", "pk_org", "code", "name", "pk_marbasclass", "pk_measdoc", "pk_mattaxes", "enablestate", "version"));
        MaterialMeasRateValidator measRateValidator = new MaterialMeasRateValidator();
        MaterialConvertValidator convertValidator = new MaterialConvertValidator(oldVO);
        MaterialTaxtypeUniqueValidator taxtypeUniqueValidator = new MaterialTaxtypeUniqueValidator(oldVO);
        RefPkExistsValidator refExistsValidator = new RefPkExistsValidator(new String[]{"pk_marbasclass"});
        MaterialBaseClassValidator classValidator = new MaterialBaseClassValidator();
        MaterialMainMeasdocRefValidator measdocValidator = new MaterialMainMeasdocRefValidator(oldVO);
        MaterialUniqueRuleValidator uniqueValidator = new MaterialUniqueRuleValidator();
        MaterialRetailRuleValidator retailRuleValidator = new MaterialRetailRuleValidator(oldVO);
        MaterialIshproitemsValidator ishproitemsValidator = new MaterialIshproitemsValidator();
        MaterialFeatureclassValueValidator featureclassValueValidator = new MaterialFeatureclassValueValidator();
        MaterialBasClassUpdateValidator orgclassValidator = new MaterialBasClassUpdateValidator(oldVO);
        return new Validator[]{notNullValidator, measRateValidator, convertValidator, taxtypeUniqueValidator, refExistsValidator, classValidator, orgclassValidator, measdocValidator, uniqueValidator, new SingleDistributedUpdateValidator(), retailRuleValidator, ishproitemsValidator, featureclassValueValidator};
    }

    protected void updatelockOperate(MaterialVO vo) throws BusinessException {
        this.lockSourcePKs(vo);
        super.updatelockOperate(vo);
    }

    private void filterBreakUniqueRuleSelfVOs(Map<String, List<MaterialVO>> sourcePk_voList_map, ErrorLogUtil util) throws BusinessException {
        Map<MaterialVO, List<String>> map = MaterialUniqueUtil.getBreakRuleofMaterialVOsSelf(sourcePk_voList_map);
        if (map != null && map.size() > 0) {
            Map<String, List<String>> result = new HashMap();

            for(MaterialVO material : map.keySet()) {
                List<String> breakRuleList = (List)map.get(material);
                if (breakRuleList != null && breakRuleList.size() != 0) {
                    String errmsg = NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0190", (String)null, new String[]{material.getVersion().toString(), StringUtil.toString(breakRuleList.toArray(new String[0]), ",")});
                    List<String> list = (List)result.get(material.getPk_source());
                    if (list == null) {
                        list = new LinkedList();
                        result.put(material.getPk_source(), list);
                    }

                    list.add(errmsg);
                }
            }

            for(String pk_source : result.keySet()) {
                MaterialVO material = (MaterialVO)((List)sourcePk_voList_map.get(pk_source)).iterator().next();
                StringBuilder errMsg = new StringBuilder();

                for(Object msg : (List)result.get(pk_source)) {
                    errMsg.append("\n").append(msg);
                }

                util.writeLogMsg(new String[]{NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0133", (String)null, new String[]{material.getCode(), errMsg.toString()})});
                sourcePk_voList_map.remove(material.getPk_source());
            }
        }

    }

    private void filterCanUpgradeVO(Map<String, List<MaterialVO>> sourcePk_voList_map, ErrorLogUtil util) throws BusinessException {
        IValidationService validateService = ValidationFrameworkUtil.createValidationService(new Validator[]{new MaterialDataUpgradeValidator(), new MaterialUniqueRuleValidator(), new SingleDistributedUpdateValidator()});
        List<String> sourcePkList = new ArrayList();

        for(String pk_source : sourcePk_voList_map.keySet()) {
            List<MaterialVO> list = (List)sourcePk_voList_map.get(pk_source);
            if (list != null && list.size() > 0) {
                try {
                    validateService.validate(list.toArray(new MaterialVO[0]));
                } catch (ValidationException e) {
                    MaterialVO vo = (MaterialVO)list.iterator().next();
                    StringBuilder errMsg = new StringBuilder();

                    for(ValidationFailure failure : e.getFailures()) {
                        errMsg.append("\n").append(failure.getMessage());
                    }

                    util.writeLogMsg(new String[]{NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0134", (String)null, new String[]{vo.getCode(), errMsg.toString()})});
                    sourcePkList.add(vo.getPk_source());
                }
            }
        }

        for(String pk_source : sourcePkList) {
            sourcePk_voList_map.remove(pk_source);
        }

    }

    private IMaterialAssignService getAssignService() {
        if (this.assignService == null) {
            this.assignService = (IMaterialAssignService)NCLocator.getInstance().lookup(IMaterialAssignService.class);
        }

        return this.assignService;
    }

    private BaseDAO getBaseDAO() {
        return new BaseDAO();
    }

    private IBillcodeManage getBillcodeManage() {
        if (this.billcodeManage == null) {
            this.billcodeManage = (IBillcodeManage)NCLocator.getInstance().lookup(IBillcodeManage.class);
        }

        return this.billcodeManage;
    }

    private MaterialVO getLatestVO(MaterialVO vo, MaterialVO[] vos) {
        if (vo.getLatest().booleanValue()) {
            return vo;
        } else {
            if (!ArrayUtils.isEmpty(vos)) {
                for(MaterialVO materialVO : vos) {
                    if (materialVO.getLatest().booleanValue()) {
                        return materialVO;
                    }
                }
            }

            return null;
        }
    }

    private MaterialVO getNewVersionData(MaterialVO vo, MaterialVO oldVO) throws DAOException {
        vo.setPk_source(oldVO.getPk_source());
        Integer version = this.queryMaxVersion(vo.getPk_source());
        vo.setVersion(version + 1);
        vo.setLatest(UFBoolean.TRUE);
        vo.setPrimaryKey((String)null);
        vo.setModifier((String)null);
        vo.setModifiedtime((UFDateTime)null);
        BDAuditInfoUtil.addData(new SuperVO[]{vo});
        MaterialConvertVO[] converts = vo.getMaterialconvert();
        if (converts != null && converts.length > 0) {
            for(int i = 0; i < converts.length; ++i) {
                converts[i].setPrimaryKey((String)null);
                converts[i].setPk_material((String)null);
                converts[i].setStatus(2);
            }
        }

        return vo;
    }

    private MaterialVO[] getSynCodeVOs(MaterialVO vo, MaterialVO[] oldVOs) {
        if (ArrayUtils.isEmpty(oldVOs)) {
            return null;
        } else {
            MaterialVO[] newVOs = new MaterialVO[oldVOs.length];

            for(int i = 0; i < oldVOs.length; ++i) {
                newVOs[i] = (MaterialVO)oldVOs[i].clone();
                newVOs[i].setCode(vo.getCode());
            }

            return newVOs;
        }
    }

    private MaterialVO[] getUpdateVOByNewCode(MaterialVO[] oldVOs, MaterialVO vo) {
        List<MaterialVO> vos = new ArrayList();

        for(MaterialVO oldVO : oldVOs) {
            if (!oldVO.getPrimaryKey().equals(vo.getPrimaryKey())) {
                MaterialVO newVO = (MaterialVO)oldVO.clone();
                newVO.setCode(vo.getCode());
                vos.add(newVO);
            }
        }

        return (MaterialVO[])vos.toArray(new MaterialVO[0]);
    }

    private MaterialVO insertWithAutoCode(MaterialVO vo, BillCodeContext billCodeContext) throws BusinessException {
        boolean sucessed = false;

        while(!sucessed) {
            try {
                if (this.isTempCode(vo) && billCodeContext != null && !billCodeContext.isPrecode()) {
                    String billcode = this.getBillcodeManage().getBillCode_RequiresNew("material", vo.getPk_group(), vo.getPk_org(), vo);
                    vo.setCode(billcode);
                }

                vo = (MaterialVO)super.insertVO(vo);
                sucessed = true;
                break;
            } catch (Exception var5) {
                if (billCodeContext != null && "32001".equals(var5.getMessage())) {
                    this.getBillcodeManage().AbandonBillCode_RequiresNew("material", vo.getPk_group(), vo.getPk_org(), vo.getCode());
                    if (!billCodeContext.isPrecode()) {
                        vo.setCode("material_temp_code");
                        continue;
                    }
                }

                throw var5;
            }
        }

        return vo;
    }

    private boolean isTempCode(MaterialVO vo) {
        return "material_temp_code".equals(vo.getCode());
    }

    private boolean isOrgData(MaterialVO vo) {
        return !vo.getPk_group().equals(vo.getPk_org()) && !vo.getPk_org().equals("GLOBLE00000000000000");
    }

    private void lockSourcePKs(MaterialVO... vos) throws BusinessException {
        String[] sourcePks = new String[vos.length];

        for(int i = 0; i < sourcePks.length; ++i) {
            sourcePks[i] = vos[i].getPk_source();
        }

        BDPKLockUtil.lockString(sourcePks);
    }

    private Map<String, List<MaterialVO>> queryAllVersionData(String... pk) throws BusinessException {
        if (pk != null && pk.length != 0) {
            Set<String> pkSet = new HashSet();

            for(int i = 0; i < pk.length; ++i) {
                pkSet.add(pk[i]);
            }

            InSqlBatchCaller caller = new InSqlBatchCaller((String[])pkSet.toArray(new String[0]));
            Map<String, List<MaterialVO>> sourcePk_voList_map = null;

            try {
                sourcePk_voList_map = (Map)caller.execute(new IInSqlBatchCallBack() {
                    Map<String, List<MaterialVO>> map = new HashMap();

                    public Object doWithInSql(String inSql) throws BusinessException, SQLException {
                        Collection<MaterialVO> coll = MaterialBaseInfoServiceImpl.this.getBaseDAO().retrieveByClause(MaterialVO.class, "pk_source in " + inSql);
                        for(MaterialVO vo : coll.toArray(new MaterialVO[0])) {
                            String pk_source = vo.getPk_source();
                            List<MaterialVO> versionList = (List)this.map.get(pk_source);
                            if (versionList == null) {
                                versionList = new ArrayList();
                                this.map.put(pk_source, versionList);
                            }

                            versionList.add(vo);
                        }

                        return this.map;
                    }
                });
                return sourcePk_voList_map;
            } catch (SQLException e) {
                throw new BusinessException(e.getMessage(), e);
            }
        } else {
            return null;
        }
    }

    private MaterialVO queryLatestMaterial(String pk_source, Integer version) throws DAOException {
        SQLParameter param = new SQLParameter();
        param.addParam(pk_source);
        param.addParam(version);
        Collection<MaterialVO> col = this.getBaseDAO().retrieveByClause(MaterialVO.class, "pk_source = ? and version = ?", param);
        MaterialVO latestVO = (MaterialVO)col.iterator().next();
        return latestVO;
    }

    private MaterialVO[] queryMaterialOldVOsWhenCodeChanged(MaterialVO vo, MaterialVO oldVO) throws BusinessException {
        if (StringUtils.equals(vo.getCode(), oldVO.getCode())) {
            return null;
        } else {
            String var10000 = vo.getPk_source();
            String condition = "pk_source = '" + var10000 + "' and pk_material <> '" + vo.getPrimaryKey() + "'";
            Collection<MaterialVO> col = this.getBaseDAO().retrieveByClause(MaterialVO.class, condition);
            return col.isEmpty() ? null : (MaterialVO[])col.toArray(new MaterialVO[0]);
        }
    }

    private Integer queryMaxVersion(String pk_source) throws DAOException {
        SQLParameter param = new SQLParameter();
        String querySql = "select max(version) from " + MaterialVO.getDefaultTableName() + " where pk_source = ?";
        param.addParam(pk_source);
        Integer version = (Integer)this.getBaseDAO().executeQuery(querySql, param, new ColumnProcessor());
        return version;
    }

    private MaterialVO queryOldVO(String pk_material) throws DAOException, BusinessException {
        MaterialVO oldVO = (MaterialVO)this.getBaseDAO().retrieveByPK(MaterialVO.class, pk_material, new String[]{"pk_material", "code", "pk_source", "ts"});
        if (oldVO == null) {
            throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0128"));
        } else {
            return oldVO;
        }
    }

    private void returnBillCode(MaterialVO vo) throws BusinessException {
        BillCodeContext billCodeContext = this.getBillcodeManage().getBillCodeContext("material", vo.getPk_group(), vo.getPk_org());
        if (billCodeContext != null) {
            this.getBillcodeManage().returnBillCodeOnDelete("material", vo.getPk_group(), vo.getPk_org(), vo.getCode(), vo);
        }

    }

    private void setVersionField(MaterialVO vo, MaterialVO oldVO) {
        vo.setPk_source(oldVO.getPk_source());
        vo.setLatest(oldVO.getLatest());
        vo.setVersion(oldVO.getVersion());
    }

    private MaterialVO[] synMaterialCode(MaterialVO vo, MaterialVO oldVO) throws BusinessException {
        MaterialVO[] vos = null;
        if (!StringUtils.equals(vo.getCode(), oldVO.getCode())) {
            List<MaterialVO> list = (List)this.queryAllVersionData(vo.getPk_source()).get(vo.getPk_source());
            if (list.isEmpty()) {
                return null;
            }

            MaterialVO[] oldVOs = (MaterialVO[])list.toArray(new MaterialVO[0]);
            MaterialVO[] var7 = this.getUpdateVOByNewCode(oldVOs, vo);
            BDAuditInfoUtil.updateData(var7);
            BDCommonEventUtil eventUtil = new BDCommonEventUtil(this.getMDId());
            eventUtil.setOldObjs(oldVOs);
            eventUtil.dispatchUpdateBeforeEvent((Object[])var7);
            this.getPersistenceUtil().updateVO(var7);
            this.notifyVersionChangeWhenDataUpdated(vo);
            vos = (MaterialVO[])this.retrieveVO(VOArrayUtil.getPrimaryKeyArray(oldVOs));
            eventUtil.dispatchUpdateAfterEvent((Object[])vos);
        }

        return vos;
    }

    private void synMaterialVersionForDelete(MaterialVO vo) throws BusinessException {
        if (vo.getLatest().booleanValue()) {
            Integer version = this.queryMaxVersion(vo.getPk_source());
            if (version != null) {
                this.updateMaterialLatesetFlag(vo.getPk_source(), version, true);
                MaterialVO latestVO = this.queryLatestMaterial(vo.getPk_source(), version);
                this.getMaterialVersionDAO().updateMaterialVersion(latestVO);
            } else {
                this.getMaterialVersionDAO().deleteMaterialVersion(vo);
                this.returnBillCode(vo);
            }

        }
    }

    private void synMaterialVersionForUpgrade(MaterialVO[] vos, String[] updateFields) throws BusinessException {
        List<MaterialVO> latestVOs = new ArrayList();

        for(int i = 0; i < vos.length; ++i) {
            if (vos[i].getLatest().booleanValue()) {
                latestVOs.add(vos[i]);
            }
        }

        this.getMaterialVersionDAO().updateMaterialVersion(updateFields, (MaterialVO[])latestVOs.toArray(new MaterialVO[0]));
    }

    private void assignMaterial(MaterialVO[] vos) throws BusinessException {
        String pk_group = InvocationInfoProxy.getInstance().getGroupId();
        String[] pk_materials = new String[vos.length];

        for(int i = 0; i < vos.length; ++i) {
            pk_materials[i] = vos[i].getPk_material();
        }

        ((IMaterialAssignService)NCLocator.getInstance().lookup(IMaterialAssignService.class)).assignByPks(pk_materials, new String[]{pk_group}, false);
    }

    private void updateMaterialLatesetFlag(String pk_source, Integer version, boolean latest) throws BusinessException {
        String updateSql = "update " + MaterialVO.getDefaultTableName() + " set latest = ? where pk_source = ? and version = ?";
        SQLParameter param_up = new SQLParameter();
        SQLParameter param_qry = new SQLParameter();
        if (latest) {
            param_up.addParam("Y");
        } else {
            param_up.addParam("N");
        }

        param_up.addParam(pk_source);
        param_up.addParam(version);
        param_qry.addParam(pk_source);
        param_qry.addParam(version);
        this.getBaseDAO().executeUpdate(updateSql, param_up);
        Collection<MaterialVO> col = this.getBaseDAO().retrieveByClause(MaterialVO.class, "pk_source = ? and version = ?", param_qry);
        if (!CollectionUtils.isEmpty(col)) {
            BDCommonEventUtil eventUtil = new BDCommonEventUtil(this.getMDId());
            MaterialVO[] vos = (MaterialVO[])col.toArray(new MaterialVO[0]);
            eventUtil.dispatchUpdateAfterEvent(vos);
            this.notifyVersionChangeWhenDataUpdated(vos[0]);
        }

    }

    public void deleteMaterial_RequiresNew(MaterialVO vo) throws BusinessException {
        boolean deleteState = true;

        try {
            if (vo != null && vo.getEnablestate() != null && vo.getEnablestate().equals(1)) {
                this.deleteVONoCheck(vo);
            } else {
                this.deleteVO(vo);
            }
        } catch (BusinessException e) {
            deleteState = false;
            Logger.error(e.getMessage());
            String caption = NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "110140mag0389", (String)null, new String[]{OrgUtil.getOrgName(vo.getPk_org()), vo.getCode(), vo.getName()});
            AnsyDeleteMessageSender.getInstance().sendMessage(caption, e.getMessage());
            throw e;
        }

        if (deleteState) {
            String caption = NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "110140mag0390", (String)null, new String[]{OrgUtil.getOrgName(vo.getPk_org()), vo.getCode(), vo.getName()});
            AnsyDeleteMessageSender.getInstance().sendMessage(caption, caption);
        }

    }

    private ILightScheduler getLightScheduler() {
        if (this.lightScheduler == null) {
            this.lightScheduler = (ILightScheduler)NCLocator.getInstance().lookup(ILightScheduler.class);
        }

        return this.lightScheduler;
    }

    private MaterialVO[] getAfterUpdatevos(SuperVO[] supervos) throws BusinessException {
        List<String> pkList = VOUtil.extractFieldValues(supervos, "pk_material", (IFilter)null);
        MaterialVO[] vos = null;
        InSqlBatchCaller caller = new InSqlBatchCaller((String[])pkList.toArray(new String[0]));

        try {
            List<MaterialVO> list = (List)caller.execute(new IInSqlBatchCallBack() {
                List<MaterialVO> list = new ArrayList();

                public Object doWithInSql(String inSql) throws BusinessException, SQLException {
                    Collection<MaterialVO> col = MaterialBaseInfoServiceImpl.this.getBaseDAO().retrieveByClause(MaterialVO.class, "pk_material in " + inSql);
                    if (col != null && col.size() > 0) {
                        this.list.addAll(col);
                    }

                    return this.list;
                }
            });
            vos = (MaterialVO[])list.toArray(new MaterialVO[0]);
            return vos;
        } catch (SQLException e) {
            Logger.error(e.getMessage(), e);
            throw new BusinessException(e.getMessage(), e);
        }
    }

    private void getMaterialvos(SuperVO[] currentvos, MaterialVO[] vos, List<SuperVO> list) {
        if (currentvos != null && currentvos.length > 0) {
            List<String> marlist = VOUtil.extractFieldValues(vos, "pk_material", (IFilter)null);

            for(int i = 0; i < vos.length; ++i) {
                for(int j = 0; j < currentvos.length; ++j) {
                    if (marlist.contains(currentvos[j].getPrimaryKey())) {
                        list.add(currentvos[j]);
                    } else {
                        list.add(vos[i]);
                    }
                }
            }
        } else {
            for(int i = 0; i < vos.length; ++i) {
                list.add(vos[i]);
            }
        }

    }

    private void resetMaterialVos(SuperVO[] vos, String delperson, UFDateTime time) {
        for(SuperVO vo : vos) {
            vo.setAttributeValue("deletestate", 1);
            vo.setAttributeValue("delperson", delperson);
            vo.setAttributeValue("deltime", time);
        }

    }

    public void ansyDeleteMaterial(MaterialVO[] materialvos) throws BusinessException {
        if (materialvos.length < 100) {
            this.ansyDeleteMaterial1(materialvos);
        } else {
            List<MaterialVO> materials = new ArrayList();

            for(int i = 0; i < materialvos.length; ++i) {
                materials.add(materialvos[i]);
            }

            for(List<MaterialVO> list_material : this.subListBySegment(materials, 100)) {
                this.ansyDeleteMaterial1((MaterialVO[])list_material.toArray(new MaterialVO[0]));
            }
        }

    }

    public List<List<MaterialVO>> subListBySegment(List<MaterialVO> data, int segments) {
        List<List<MaterialVO>> result = new ArrayList();
        int size = data.size();
        if (size > 0 && segments > 0) {
            int count = size / segments;
            List<MaterialVO> cutList = null;

            for(int i = 0; i < segments; ++i) {
                if (i == segments - 1) {
                    cutList = data.subList(count * i, size);
                } else {
                    cutList = data.subList(count * i, count * (i + 1));
                }

                result.add(cutList);
            }
        } else {
            result.add(data);
        }

        return result;
    }

    public void ansyDeleteMaterial1(MaterialVO[] materialvos) throws BusinessException {
        ValueObjWithErrLog errorlog = super.disableVO(materialvos);
        SuperVO[] currentvos = errorlog.getVos();
        String delperson = AuditInfoUtil.getCurrentUser();
        UFDateTime currenttime = AuditInfoUtil.getCurrentTime();
        String mdid = "c7dc0ccd-8872-4eee-8882-160e8f49dfad";
        List<SuperVO> list = new ArrayList();
        this.getMaterialvos(currentvos, materialvos, list);
        SuperVO[] needdeletevos = (SuperVO[])list.toArray(new SuperVO[0]);
        this.resetMaterialVos(needdeletevos, delperson, currenttime);
        (new BaseDAO()).updateVOArray(needdeletevos, new String[]{"deletestate", "delperson", "deltime"});
        TaskConfig taskconfig = (new TaskConfigBuilder()).name("delete").immediate().assign().bind();
        taskconfig.setDef1("10140material");
        taskconfig.setModule("uapbd");
        taskconfig.setDef3((new UFDateTime(new Date(TimeService.getInstance().getTime()))).toString());
        String taskid = taskconfig.getId();
        SuperVO[] afterVos = this.getAfterUpdatevos(needdeletevos);
        ReallyTread thread = new ReallyTread(new MaterialAnsyDelete(), afterVos, delperson, taskid, mdid);
        this.getLightScheduler().addTask(thread, taskconfig);
    }

    public ErrLogReturnValue checkBeforeUpdateMabasclass(MaterialVO material) throws BusinessException {
        MaterialVO oldVO = (MaterialVO)this.getBaseDAO().retrieveByPK(MaterialVO.class, material.getPk_material());
        if (oldVO == null) {
            return null;
        } else if (oldVO.getPk_marbasclass().equals(material.getPk_marbasclass())) {
            return null;
        } else {
            ErrLogReturnValue returnvalue = new ErrLogReturnValue((ErrLogResult)null, UFBoolean.FALSE, 1);

            try {
                IMaterailUpdateCheckForGL checkservice = (IMaterailUpdateCheckForGL)NCLocator.getInstance().lookup(IMaterailUpdateCheckForGL.class);
                boolean isreferenced = checkservice.isReferenceMaBasClass(oldVO, material);
                return !isreferenced ? null : returnvalue;
            } catch (ComponentNotFoundException ex) {
                Logger.error(ex.getMessage(), ex.getCause());
                return null;
            } catch (Exception ex) {
                Logger.error(ex.getMessage(), ex.getCause());
                return null;
            }
        }
    }

    private void deleteGoodsRef(MaterialVO oldvo, MaterialVO vo) throws BusinessException {
        if ((oldvo.getRetail().booleanValue() || oldvo.getElectronicsale().booleanValue()) && (StringUtils.isEmpty(oldvo.getPk_marasstframe()) || "~".equals(oldvo.getPk_marasstframe()))) {
            if (!vo.getRetail().booleanValue() && !vo.getElectronicsale().booleanValue()) {
                this.getBaseDAO().deleteByClause(GoodsRefVO.class, "pk_material='" + vo.getPk_source() + "'");
                return;
            }

            if (StringUtils.isNotEmpty(vo.getPk_marasstframe()) && !"~".equals(oldvo.getPk_marasstframe())) {
                String sql = "select devmodule,implclassname from bd_goodsref_validator";
                List<Object[]> result = (List)this.getBaseDAO().executeQuery(sql, new ArrayListProcessor());
                boolean flag = false;
                if (result != null && result.size() > 0) {
                    for(Object[] busiVal : result) {
                        IMaterialBaseInfoEditValidatorForFrame materialBaseInfoEditValidatorForFrame = (IMaterialBaseInfoEditValidatorForFrame)ObjectCreator.newInstance((String)busiVal[0], (String)busiVal[1]);
                        flag = materialBaseInfoEditValidatorForFrame.materialOIDisQuoteForFrame(vo.getPk_source());
                        if (flag) {
                            return;
                        }
                    }
                }

                if (!flag) {
                    this.getBaseDAO().deleteByClause(GoodsRefVO.class, "pk_material='" + vo.getPk_source() + "'");
                }
            }
        }

    }

    private void checkRequiredProperties(MaterialVO[] vos) throws BusinessException {
        if (!ArrayUtils.isEmpty(vos)) {
            List<String> requiredField = new ArrayList(20);

            for(MaterialVO materialVO : vos) {
                UFBoolean flag_drug = materialVO.getFlag_drug();
                if (flag_drug != null && flag_drug.booleanValue()) {
                    if (StringUtils.isEmpty(materialVO.getPk_measdoc_base())) {
                        requiredField.add("基本包装单位");
                    }

                    if (StringUtils.isEmpty(materialVO.getFactor_fb())) {
                        requiredField.add("主计量单位/基本包装单位");
                    }

                    if (StringUtils.isEmpty(materialVO.getPk_measdoc_med())) {
                        requiredField.add("医疗含量单位");
                    }

                    if (StringUtils.isEmpty(materialVO.getFactor_mb())) {
                        requiredField.add("医疗含量单位/基本包装单位");
                    }

                    if (StringUtils.isEmpty(materialVO.getPk_dosage())) {
                        requiredField.add("剂型");
                    }

                    if (StringUtils.isEmpty(materialVO.getEu_muputype())) {
                        requiredField.add("取整方式");
                    }

                    if (StringUtils.isEmpty(materialVO.getEu_pois())) {
                        requiredField.add("毒麻分类");
                    }

                    if (requiredField.size() > 0) {
                        throw new BusinessException("药品，下列字段不能为空：" + requiredField.toString());
                    }
                }

                UFBoolean qualitymanflag = materialVO.getQualitymanflag();
                if (qualitymanflag != null && qualitymanflag.booleanValue()) {
                    if (materialVO.getQualityunit() == null) {
                        requiredField.add("保质期单位");
                    }

                    if (materialVO.getQualitynum() == null) {
                        requiredField.add("保质期");
                    }

                    if (materialVO.getWholemanaflag() == null || !materialVO.getWholemanaflag().booleanValue()) {
                        requiredField.add("批次管理");
                    }

                    if (requiredField.size() > 0) {
                        throw new BusinessException("保质期管理，下列字段不能为空：" + requiredField.toString());
                    }
                }

                UFBoolean serialmanaflag = materialVO.getSerialmanaflag();
                if (serialmanaflag != null && serialmanaflag.booleanValue()) {
                    if (StringUtils.isEmpty(materialVO.getSernumunit())) {
                        requiredField.add("序列号单位");
                    }

                    if (requiredField.size() > 0) {
                        throw new BusinessException("进行序列号管理，下列字段不能为空：" + requiredField.toString());
                    }
                }

                String eu_pdprice = materialVO.getEu_pdprice();
                if (StringUtils.isNotEmpty(eu_pdprice) && "0".equals(eu_pdprice)) {
                    if (materialVO.getSaleprice() == null) {
                        requiredField.add("零售价格");
                    }

                    if (requiredField.size() > 0) {
                        throw new BusinessException("零售价计价方式为固定价格，下列字段不能为空：" + requiredField.toString());
                    }
                }
            }

        }
    }

    private void dealDrugInfo(MaterialVO[] vos) throws BusinessException {
        if (!ArrayUtils.isEmpty(vos)) {
            Map<String, DefdocVO> defdocMap = this.getDefDocMap("1001YY10000000008CYY", "GLOBLE00000000000000");

            for(MaterialVO materialVO : vos) {
                UFBoolean flag_drug = materialVO.getFlag_drug();
                if (materialVO.getOutcloselowerlimit() == null) {
                    materialVO.setOutcloselowerlimit(UFDouble.ZERO_DBL);
                }

                if (materialVO.getIntolerance() == null) {
                    materialVO.setIntolerance(UFDouble.ZERO_DBL);
                }

                if (materialVO.getOuttolerance() == null) {
                    materialVO.setOuttolerance(UFDouble.ZERO_DBL);
                }

                if (flag_drug == null || !flag_drug.booleanValue()) {
                    this.deleteMaterialConvertForNotDrug(materialVO);
                    materialVO.setPk_measdoc_base((String)null);
                    materialVO.setFactor_fb((String)null);
                    materialVO.setPk_measdoc_med((String)null);
                    materialVO.setFactor_mb((String)null);
                    materialVO.setPk_dosage((String)null);
                    materialVO.setEu_pois((String)null);
                    materialVO.setName_chem((String)null);
                    materialVO.setPk_anti((String)null);
                    materialVO.setEu_muputype((String)null);
                    materialVO.setEu_manufactory((String)null);
                    materialVO.setPk_pharm((String)null);
                    materialVO.setFlag_base(UFBoolean.FALSE);
                    materialVO.setFlag_iv(UFBoolean.FALSE);
                    materialVO.setFlag_rsa(UFBoolean.FALSE);
                    materialVO.setFlag_sd(UFBoolean.FALSE);
                    materialVO.setFlag_rm(UFBoolean.FALSE);
                    materialVO.setFlag_reag(UFBoolean.FALSE);
                    materialVO.setFlag_vacc(UFBoolean.FALSE);
                    materialVO.setFlag_province(UFBoolean.FALSE);
                    materialVO.setFlag_refrigeration(UFBoolean.FALSE);
                    materialVO.setFlag_highrisk(UFBoolean.FALSE);
                    materialVO.setFlag_nutrition(UFBoolean.FALSE);
                    materialVO.setFlag_nuclide(UFBoolean.FALSE);
                    materialVO.setFlag_st(UFBoolean.FALSE);
                    materialVO.setFlag_gmp(UFBoolean.FALSE);
                    materialVO.setFlag_tpn(UFBoolean.FALSE);
                    materialVO.setUsagenote((String)null);
                    materialVO.setPk_chcate((String)null);
                    materialVO.setDememo((String)null);
                    materialVO.setIndica((String)null);
                    materialVO.setConstr((String)null);
                    materialVO.setReact((String)null);
                    materialVO.setQuan_def((UFDouble)null);
                    materialVO.setPk_measdoc_def((String)null);
                    materialVO.setPk_freq_def((String)null);
                    materialVO.setPk_usage_def((String)null);
                }

                if (StringUtils.isNotEmpty(materialVO.getEu_pois())) {
                    DefdocVO defdoc_pois = (DefdocVO)defdocMap.get(materialVO.getEu_pois());
                    if (defdoc_pois != null) {
                        materialVO.setDt_pois(defdoc_pois.getCode());
                    }
                }
            }

        }
    }

    private void deleteMaterialConvertForNotDrug(MaterialVO materialVO) throws BusinessException {
        if (materialVO != null) {
            MaterialConvertVO[] convertVOs = materialVO.getMaterialconvert();
            String pk_measdoc_base = materialVO.getPk_measdoc_base();
            if (!ArrayUtils.isEmpty(convertVOs) && !StringUtils.isEmpty(pk_measdoc_base)) {
                String pk_measdoc = materialVO.getPk_measdoc();
                List<MaterialConvertVO> newConvertVOs = new ArrayList();

                for(MaterialConvertVO materialConvertVO : convertVOs) {
                    if (pk_measdoc_base.equals(materialConvertVO.getPk_measdoc())) {
                        if (materialVO.getStatus() == 2) {
                            continue;
                        }

                        if (materialVO.getStatus() == 1) {
                            materialConvertVO.setStatus(3);
                        }
                    }

                    if (StringUtils.isNotEmpty(pk_measdoc) && pk_measdoc.equals(materialConvertVO.getPk_measdoc())) {
                        materialConvertVO.setFlag_ip(UFBoolean.TRUE);
                        materialConvertVO.setIsstockmeasdoc(UFBoolean.TRUE);
                    }

                    newConvertVOs.add(materialConvertVO);
                }

                if (newConvertVOs != null && newConvertVOs.size() > 0) {
                    materialVO.setMaterialconvert((MaterialConvertVO[])newConvertVOs.toArray(new MaterialConvertVO[0]));
                }

            }
        }
    }

    private void dealMarAsstFrameInfo(MaterialVO[] vos) throws BusinessException {
        if (!ArrayUtils.isEmpty(vos)) {
            IMaterialHpcService hpcService = (IMaterialHpcService)NCLocator.getInstance().lookup(IMaterialHpcService.class);

            for(MaterialVO materialVO : vos) {
                boolean isInclude = hpcService.checkMarAsstFrameIsIncludeCost(materialVO.getPk_group(), materialVO.getPk_marasstframe());
                if (!isInclude) {
                    ExceptionUtils.wrappBusinessException("辅助属性结构必须导入且需包含成本价");
                }
            }

        }
    }

    private void dealMaterialmnecode(MaterialVO[] vos) throws BusinessException {
        if (!ArrayUtils.isEmpty(vos)) {
            for(MaterialVO materialVO : vos) {
                if (StringUtils.isEmpty(materialVO.getMaterialmnecode())) {
                    materialVO.setMaterialmnecode(this.getPinYinHeadChar(materialVO.getName()));
                }
            }

        }
    }

    private String getPinYinHeadChar(String strSrc) {
        if (strSrc != null && strSrc.trim().length() != 0) {
            String strConvert = "";

            for(int i = 0; i < strSrc.length(); ++i) {
                char charWord = strSrc.charAt(i);
                String[] strPinYins = PinyinHelper.toHanyuPinyinStringArray(charWord);
                strConvert = strConvert + (strPinYins != null && strPinYins.length > 0 ? strPinYins[0].charAt(0) : charWord);
            }

            return strConvert;
        } else {
            return strSrc;
        }
    }

    private Map<String, DefdocVO> getDefDocMap(String pk_defdoclist, String pk_org) throws BusinessException {
        Map<String, DefdocVO> defdocMap = new HashMap(20);
        IDefdocQryService defdocQueryService = (IDefdocQryService)NCLocator.getInstance().lookup(IDefdocQryService.class);
        DefdocVO[] defdocVOs = defdocQueryService.queryDefdocVOsByDoclistPk(pk_defdoclist, pk_org, InvocationInfoProxy.getInstance().getGroupId());
        if (defdocVOs != null && defdocVOs.length > 0) {
            for(DefdocVO defdocVO : defdocVOs) {
                defdocMap.put(defdocVO.getPk_defdoc(), defdocVO);
            }
        }

        return defdocMap;
    }
}
